<template>
	<view class="page-bg">
		<view class="top-tab-bg" :style="{top: stickyTop + 'px'}">
			<view class="tab-left-bg">
				<view class="selected-tab-bg">焊接轨迹</view>
				<!-- <view class="unselect-tab-bg">拍照轨迹</view> -->
			</view>
			<image class="tab-right-img" src="../static/robot/icon_point_edit.png" @click="changeMoveViewShowOrHide">
			</image>
		</view>
		<view v-if="!isShowMoveView" class="drag-sort2" :style="{ height: boxHeight}">
			<view v-for="(item, index) in list" :key="index" class="drag-sort-item2">
				<view class="text-item" :class="item.data?'has-get-point':'no-get-point'">
					{{item.name}}{{item.data?'(已记录)':'(未记录)'}}</view>
				<view class="get-point" @click="getPoint(item, index)">取点</view>
			</view>
		</view>
		<view class="console-feature-bg">
			<!-- <drag-sorts ref="mydragSort" :list="list" @change="onDragSortChange" @longpressItem="longpressItem"
				:isOperated="isShowMoveView" @dragItemClick="dragItemClick" @deleteList="deleteList"
				@dragList="dragList"></drag-sorts> -->
			<movable-area class="drag-sort" :style="{ height: boxMoveHeight }" id="drag">
				<movable-view v-for="(item, index) in currentList" :key="index" :x="item.x" :data-index="index"
					@touchstart="touchstart" @touchmove.stop.prevent="touchmove" @touchend="touchend" v-if="isShowMoveView"
					@click="close(index, item)" @longpress="longpressDragItem" :y="item.y" :direction="direction"
					disabled damping="40" :animation="item.animation" class="drag-sort-item"
					:style="{ height: height+'px' }">

					<view class="text-item" :class="item.data?'has-get-point':'no-get-point'">
						{{item.name}}{{item.data?'(已记录)':'(未记录)'}}</view>
					<view class="get-point">取点</view>
					<image src="/static/icon_feature_remove.png" alt="" class="icon-close"
						v-if="!item.isFixed && isOperated"></image>

				</movable-view>
			</movable-area>
		</view>
		<view class="add-point-bg" @click="showPopup">
			<uni-icons size="44" color="#fff" style="font-size: 20px;">+</uni-icons>
		</view>
		<uni-popup ref="refPopupAddPoint" type="center" :mask-click="true">
			<view class="device-settings-content">
				<text class="device-settings-title">添加取点</text>
				<view class="popup-content-bg">
					<view class="content-title">选择点类型</view>
					<picker mode="selector" :range="addPointTypeList" range-key="name" @change="onPointTypeChange">
						<view class="picker">
							{{selectedPointType ? selectedPointType.name : '请选择点类型'}}
						</view>
					</picker>
					<view class="btn-bg">
						<view class="btn-confirm-bg" @click="confirmAddPoint">确定</view>
						<view class="btn-cancel-bg" @click="closePopup">取消</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import robotApi from '../apis/robotApi';
	import dragSorts from '@/components/drag-sorts/index.vue';
	import * as Constants from '@/common/constants.js';
	export default {
		name: "robot-bottom-move",
		components: {
			dragSorts
		},
		data() {
			return {
				list: [],
				boxHeight: 0,
				boxMoveHeight: 0,
				testItem: {
					name: '安全点（未记录）',
					isFixed: false,
				},

				isShowMoveView: false,

				addPointTypeList: [],
				selectedPointType: null,

				direction: 'vertical',
				windowWidth: 100, //屏幕宽度
				height: 40, // 高度
				currentList: [],
				active: -1, // 当前激活的item
				index: 0, // 当前激活的item的原index
				topY: 0, // 距离顶部的距离
				topX: 0, // 距离左侧偏移位置
				deviationX: 0,
				deviationY: 0, // 偏移量
				moveToNumber: -1,

				isOperated: true, // 是否在可操作的状态
			}
		},
		props: {
			stickyTop: {
				type: Number,
				default: 84
			}
		},
		created() {},
		onShow() {
			console.log("BottomMoveView onSHow")
		},
		mounted() {
			console.log("BottomMoveView mounted")
			this.init()
			this.boxHeight = this.list.length * 60 + 5 + 'px'
			// this.boxMoveHeight = this.list.length * 60 + 5 + 'px'
			this.windowWidth = uni.upx2px(710);
		},
		watch: {
			currentList: {
				handler() {
					// this.boxHeight = this.currentList.length * (this.height + 20) + 5 + 'px';
					// this.boxMoveHeight = this.currentList.length * (this.height + 20) + 5 + 'px';
					this.moveViewHeight()
				},
				deep: true
			},
		},
		methods: {
			init() {
				this.isShowMoveView = false
				
				this.addPointTypeList = [{
						name: "安全点",
						value: 1,
						pointType: Constants.POINT_TYPE.SAFE_POINT
					},
					{
						name: "起弧点",
						value: 2,
						pointType: Constants.POINT_TYPE.ARCING_POINT
					},
					{
						name: "中间点",
						pointType: Constants.POINT_TYPE.INTERMEDIATE_POINT,
						value: 3
					},
					{
						name: "熄弧点",
						value: 4,
						pointType: Constants.POINT_TYPE.EXTINGUISHING_POINT
					},
					{
						name: "过渡点",
						value: 5,
						pointType: Constants.POINT_TYPE.TRANSITIONS_POINT
					}
				]

				this.list = [{
						name: '安全点',
						isFixed: false,
						pointType: Constants.POINT_TYPE.SAFE_POINT
					},
					{
						name: '过渡点',
						isFixed: false,
						pointType: Constants.POINT_TYPE.TRANSITIONS_POINT
					},
					{
						name: '起弧点',
						isFixed: false,
						pointType: Constants.POINT_TYPE.ARCING_POINT
					},
					{
						name: '熄弧点',
						isFixed: false,
						pointType: Constants.POINT_TYPE.EXTINGUISHING_POINT
					},
					{
						name: '过渡点',
						isFixed: false,
						pointType: Constants.POINT_TYPE.TRANSITIONS_POINT
					}
				]
				this.onUpdateCurrentList();
			},

			changeMoveViewShowOrHide() {
				this.isShowMoveView = !this.isShowMoveView
				this.moveViewHeight()
			},
			
			moveViewHeight() {
				if (this.isShowMoveView) {
					this.boxHeight = '0px'
					this.boxMoveHeight = this.currentList.length * (this.height + 20) + 5 + 'px';
				} else {
					this.boxHeight = this.currentList.length * (this.height + 20) + 5 + 'px';
					this.boxMoveHeight = '0px'
				}
			},
			
			onDragSortChange(arr) {
				console.log("onDragSortChange", JSON.stringify(arr))
				this.list = arr
			},
			longpressItem() {
				console.log("longpressItem")
			},
			dragItemClick(item, index) {
				console.log("dragItemClick")
			},
			deleteList(item, arr) {
				console.log("deleteList", JSON.stringify(arr))
				this.list = arr
			},
			dragList(arr) {
				// console.log("dragList", JSON.stringify(arr))
			},

			showPopup() {
				this.$refs.refPopupAddPoint.open()
			},
			closePopup() {
				this.$refs.refPopupAddPoint.close()
			},

			onPointTypeChange(e) {
				this.selectedPointType = this.addPointTypeList[e.detail.value]
			},
			confirmAddPoint() {
				if (this.selectedPointType) {
					this.list.push(this.selectedPointType)
					this.onUpdateCurrentList()
					this.closePopup()
				} else {
					uni.showToast({
						title: "请选择点添加"
					})
				}
			},

			getPoint(item, index) {
				robotApi.getPoint()
					.then(res => {
						if (res.code == 200 || res.code == "200") {
							this.list[index].data = res.data
							// 更新数组
							this.onUpdateCurrentList()
							// 获取到的最新点传给父组件，让父组件传给手动模板的位姿显示
							this.$emit("noticePointDataToHandTemplate", res.data, index)
						}
					})
			},
			
			parentSetListData(newList) {
				console.log("父组件给子组件设置值")
				this.list = newList
				this.onUpdateCurrentList()
			},
			
			/**
			 * 让父组件获取点集合
			 */
			parentGetListData() {
				return this.currentList
			},
			
			/**
			 * 让父组件的位姿更新最新的取点数据
			 * @param {Object} newPointData 位姿上改变的点数据
			 * @param {Object} index 最新的取点所在下标
			 */
			changeChoosePointData(newPointData, index) {
				console.log("newPointData-->" + JSON.stringify(newPointData))
				if (newPointData && index >= 0 && index < this.list.length) {
					this.list[index].data = newPointData
					this.onUpdateCurrentList()
				}
			},



			changeOperateStatus(isCanOperate) {
				this.isOperated = isCanOperate
			},
			longpressDragItem() {
				this.isOperated = true;
				// this.$emit('longpressItem');
			},
			longpress(state) {
				// this.isOperated = state;
			},
			onUpdateCurrentList(list = this.list) {
				const self = this;

				let arr = [];
				for (const key in list) {
					let height = Math.ceil((Number(key) + 1) / 5) - 1;
					let x = 0;
					if (key <= 4) {
						x = key * this.windowWidth * 0.2;
					} else {
						if ((Number(key) + 1) % 5 === 0) {
							x = 4 * this.windowWidth * 0.2;
						} else {
							x = (((Number(key) + 1) % 5) - 1) * this.windowWidth * 0.2;
						}
					}
					arr.push({
						...list[key],
						index: Number(key),
						SortNumber: Number(key),
						y: key * (this.height + 20),
						x: 0,
						animation: false
					});
				}
				this.currentList = arr;
				console.log("this.currentList--" + JSON.stringify(this.currentList))
			},
			touchstart(e) {
				if (!this.isOperated) {
					return false
				}
				// 计算 x y 轴点击位置
				var query = uni.createSelectorQuery().in(this);
				query.select('#drag').boundingClientRect();
				query.exec(res => {
					this.topY = res[0].top;
					this.topX = res[0].left;
					let touchY = e.touches[0].clientY - res[0].top;
					let touchX = e.touches[0].clientX - res[0].left;
					this.deviationY = touchY % this.height;
					this.deviationX = touchX % (this.windowWidth * 0.2);
					this.active = Number(e.currentTarget.dataset.index);
					this.index = Number(e.currentTarget.dataset.index);
				});
			},
			touchmove(e) {
				if (!this.isOperated) {
					return false
				}
				if (this.active < 0) return;
				let temY = e.touches[0].clientY - this.topY;
				let temX = e.touches[0].clientX - this.topX;
				let touchY = temY - 15;
				// let touchX = temX - this.windowWidth * 0.1;
				this.currentList[this.active].y = touchY;
				// this.currentList[this.active].x = touchX;
				this.currentList[this.active].animation = false;
				this.currentList.every((res, index) => {
					// let absX = Math.abs(touchX - res.x);
					let absY = Math.abs(touchY - res.y);

					// 设置元素定点距离多少进行重排
					if (absY > 15 && absY <= 30 && this.active != index) {
						// debugger
						// let temNumber = this.currentList[index].SortNumber;
						this.moveToNumber = this.currentList[index].SortNumber;
						// this.currentList.every((_res, _index) => {
						// 	if (_res.isShow == 0) {
						// 		return true;
						// 	}
						// console.log("index----------------->" + index + "touchY-->" + touchY + ";res.y-->" + res.y + ";absY -->" + absY)
						// 	console.log("active.sortNum-->" + this.currentList[this.active].SortNumber)
						// 	console.log("index.sortNum-->" + this.currentList[index].SortNumber)
						// 	console.log("_index.sortNum-->" + this.currentList[_index].SortNumber)
						// 	console.log("_res.sortNum-->" + _res.SortNumber)
						// 	// 判断从大像小移还是从小向大移
						// 	if (this.currentList[this.active].SortNumber < this.currentList[index].SortNumber) {
						// 		// 移动元素比目标元素所在位置小，之间元素排序--
						// 		if (
						// 			this.currentList[_index].SortNumber > this.currentList[this.active].SortNumber &&
						// 			this.currentList[_index].SortNumber <= this.currentList[index].SortNumber
						// 		) {
						// 			_res.SortNumber--;
						// 		}
						// 	} else {
						// 		// 反之++
						// 		if (
						// 			this.currentList[_index].SortNumber < this.currentList[this.active].SortNumber &&
						// 			this.currentList[_index].SortNumber >= this.currentList[index].SortNumber
						// 		) {
						// 			_res.SortNumber++;
						// 		}
						// 	}
						// 	return true;
						// }, this);
						// this.currentList[this.active].SortNumber = temNumber;
						this.currentList[this.active].SortNumber = this.moveToNumber;
						return false;
					} else {
						return true;
					}
				}, this);
			},
			touchend(e) {
				if (!this.isOperated) {
					return false
				}
				if (this.active < 0) return;
				if (this.moveToNumber < 0) return;
				this.moveUpdateCurrentList(this.moveToNumber);
				this.currentList.sort(this.compare('SortNumber'));
				if (this.currentList[this.active]) {
					this.currentList[this.active].animation = true;
				}
				this.active = -1;
				this.moveToNumber = -1
				setTimeout(() => {
					// this.$emit('dragList', this.currentList);
					this.dragList(this.currentList)
				}, 500);
			},
			// 根据排序进行重新计算位置
			moveUpdateCurrentList(index) {
				this.moveItem(this.currentList, this.active, index)
				for (const i in this.currentList) {
					let key;
					if (this.currentList[i].SortNumber || this.currentList[i].SortNumber === 0) {
						key = this.currentList[i].SortNumber;
					} else {
						key = Number(i);
					}
					let temobj = {
						...this.currentList[i]
					};
					// debugger
					// this.currentList[i].y = (Math.ceil((Number(key) + 1) / 5) - 1) * this.height;
					this.currentList[i].x = 0
					this.currentList[i].y = i * (this.height + 20);
					this.currentList[i].index = Number(i)
					this.currentList[i].SortNumber = Number(i)
					// if (index == key) {
					// 	continue;
					// } else {
					// 	// if (key <= 4) {
					// 	// 	this.currentList[i].x = key * this.windowWidth * 0.2;
					// 	// } else {
					// 	// 	if ((Number(key) + 1) % 5 === 0) {
					// 	// 		this.currentList[i].x = 4 * this.windowWidth * 0.2;
					// 	// 	} else {
					// 	// 		this.currentList[i].x = (((Number(key) + 1) % 5) - 1) * this.windowWidth * 0.2;
					// 	// 	}
					// 	// }
					// 	this.currentList[i].x = 0
					// }
				}
				// this.currentList = this.currentList.filter(v => v.isShow);
				// this.$emit('onDragSortChange', this.currentList);
				this.onDragSortChange(this.currentList)
			},
			moveItem(arr, fromIndex, toIndex) {
				// 处理负索引
				const startIdx = fromIndex < 0 ? arr.length + fromIndex : fromIndex;
				const endIdx = toIndex < 0 ? arr.length + toIndex : toIndex;
				// 检查索引有效性
				if (startIdx < 0 || startIdx >= arr.length || endIdx < 0 || endIdx >= arr.length) {
					return arr;
				}
				// 取出元素并插入到新位置
				const [item] = arr.splice(startIdx, 1);
				arr.splice(endIdx, 0, item);
				return arr;
			},
			// 关闭按钮
			close(index, item) {
				if (item.isFixed || !this.isOperated) {
					// this.$emit('dragItemClick', item, index);
					this.dragItemClick(item, index)
					return;
				};
				let _this = this;
				uni.showModal({
					title: "是否删除当前项？",
					success: (res) => {
						if (res.confirm) {
							this.toDeleteItem(item, index)
						}
					}
				})
			},
			toDeleteItem(item, index) {
				this.currentList.splice(index, 1)
				this.currentList.forEach((item, i) => {
					this.currentList[i].x = 0
					this.currentList[i].y = i * (this.height + 20);
					this.currentList[i].index = Number(i)
					this.currentList[i].SortNumber = Number(i)
				});
				// this.$emit('deleteList', item, this.currentList);
				this.deleteList(item, this.currentList)
			},
			compare(key) {
				return function(value1, value2) {
					var val1 = value1[key];
					var val2 = value2[key];
					return val1 - val2;
				};
			},
			bubbleSort(array) {
				var i = 0,
					len = array.length,
					j,
					d;
				for (; i < len; i++) {
					for (j = 0; j < len; j++) {
						if (array[i].SortNumber < array[j].SortNumber) {
							d = array[j].SortNumber;
							array[j].SortNumber = array[i].SortNumber;
							array[i].SortNumber = d;
						}
					}
				}
				return array;
			}
		}
	}
</script>

<style scoped lang="scss">
	.page-bg {
		background-color: #1e40af;
		padding: 40rpx;
	}

	.top-tab-bg {
		position: sticky;
		z-index: 9;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 0;
		margin-bottom: 20rpx;
		border-bottom: 2rpx solid rgba(37, 99, 235, 0.5);
		background-color: #1e40af;

		.tab-left-bg {
			display: flex;
			align-items: center;
		}

		.selected-tab-bg {
			margin-right: 20rpx;
			color: rgba(59, 130, 246, 1);
			font-size: 38rpx;
		}

		.unselect-tab-bg {
			margin-right: 20rpx;
			color: rgba(147, 197, 253, 0.5);
			font-size: 32rpx;
		}

		.tab-right-img {
			width: 48rpx;
			height: 48rpx;
		}
	}

	.console-feature-bg {}

	.drag-sort2 {
		width: 100%;
		// min-height: 180rpx;
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.drag-sort-item2 {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 40px;
		width: 100%;
		color: #fff;
		box-sizing: border-box;
		// background: #fff;
		border-radius: 24rpx;
		border: 2rpx solid rgba(29, 78, 216, 1);
		margin-bottom: 20px;
		padding: 20rpx;

		&.active {
			z-index: 999;
			// border-left: 1px solid #f2f2f2;
			// border-top: 1px solid #f2f2f2;
		}

		.item {
			position: relative;
			flex: 1;
			font-size: 16px;
		}
	}

	.text-item {
		color: rgba(147, 197, 253, 1);
		font-size: 36rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.get-point {
		border-radius: 16rpx;
		padding: 8rpx 30rpx;
		background-color: #3b82f6;
		color: #fff;
		font-size: 28rpx;
	}

	.icon-close {
		position: absolute;
		width: 34rpx;
		height: 34rpx;
		top: 6rpx;
		right: 6rpx;
		z-index: 999;
	}

	.has-get-point {
		color: rgba(16, 185, 129, 1)
	}

	.no-get-point {
		color: rgba(147, 197, 253, 1);
	}

	.drag-sort {
		width: 100%;
		// min-height: 180rpx;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.drag-sort-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// height: 160rpx;
		width: 100%;
		color: #fff;
		box-sizing: border-box;
		border-radius: 24rpx;
		border: 2rpx solid rgba(29, 78, 216, 1);
		margin-bottom: 20px;
		padding: 20rpx;

		&.active {
			z-index: 999;
			// border-left: 1px solid #f2f2f2;
			// border-top: 1px solid #f2f2f2;
		}

		.item {
			position: relative;
			flex: 1;
			font-size: 16px;
		}
	}

	.add-point-bg {
		position: fixed;
		bottom: 70px;
		right: 10px;
		width: 50px;
		height: 50px;
		background-color: #1890ff;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		z-index: 90;
	}

	.device-settings-content {
		background-color: #1e40af;
		padding: 30rpx;
		border-radius: 8px;
		width: 600rpx;

		.device-settings-title {
			display: flex;
			flex-direction: row;
			justify-content: center;
			font-size: 40rpx;
			margin-bottom: 40rpx;
			font-weight: 600;
			text-align: center;
			color: #fff;
		}

		.popup-content-bg {
			background-color: #1e3a8a;
			padding: 30rpx;
			border-radius: 8px;

			.content-title {
				color: #FFFFFF;
				font-size: 28rpx;
				margin-bottom: 20rpx;
			}

			.btn-bg {
				margin-top: 40rpx;
				display: flex;
				align-items: center;
			}

			.btn-confirm-bg {
				display: flex;
				align-items: center;
				justify-content: center;
				flex: 1;
				padding: 20rpx 0;
				background-color: rgba(59, 130, 246, 1);
				font-size: 28rpx;
				color: #FFFFFF;
				margin-right: 20rpx;
				border-radius: 16rpx;
			}

			.btn-cancel-bg {
				display: flex;
				align-items: center;
				justify-content: center;
				flex: 1;
				padding: 20rpx 0;
				background-color: rgba(30, 64, 175, 1);
				font-size: 28rpx;
				color: #FFFFFF;
				margin-left: 20rpx;
				border-radius: 16rpx;
				border: 2rpx solid rgba(37, 99, 235, 1);
			}
		}
	}

	input,
	.picker {
		/* width: 100%; */
		flex: 1;
		padding: 10px;
		border: 1px solid #1e40af;
		border-radius: 6px;
		font-size: 16px;
		background-color: #1e40af;
		color: #FFFFFF;
	}
</style>